import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Classname HuffmanTree 赫夫曼树：最优二叉树；该树的带权路径长度打达到最小；权值较大的结点离根较近
 * @Description  最佳实践：数据压缩和解压（文件）
 * @Date 2021/12/3 15:54
 * @Created K024851
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int arr[]={13,7,8,3,29,6,1};
        Node root = createHuffmanTree(arr);
        preOrder(root);
    }
    public static void preOrder(Node root){
        if (root !=null){
            root.preOrder();
        }else {
            System.out.println("空树不能遍历");
        }
    }

    public static  Node createHuffmanTree(int[] arr){
        List<Node> nodes = new ArrayList<Node>();
        for (int value:arr){
            nodes.add(new Node(value));
        }
        while (nodes.size()>1){
            Collections.sort(nodes);
            //取出权值最小的节点
            Node leftNode = nodes.get(0);
            //去除第二小
            Node rightNode = nodes.get(1);
            //构建新的树
            Node parent = new Node(leftNode.value+rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);
        }
        return nodes.get(0);
    }
}

class Node implements Comparable<Node>{
    int value;
    Node left;
    Node right;
    public  void preOrder(){
        System.out.println(this);
        if (this.left != null){
            this.left.preOrder();
        }
    }
    public Node(int value){
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" + "value=" + value + '}';
    }

    @Override
    public int compareTo(Node o) {
        //return 0;
        return this.value-o.value;
    }

    public Node search(int value) {
        if (value == this.value){
            return this;
        }else if (value<this.value){
            if (this.left ==null){
                return null;
            }
            return this.left.search(value);
        }else {
            if (this.right ==null){
                return null;
            }
            return this.right.search(value);
        }
    }
    public Node searchParent(int value){
        if ((this.left !=null && this.left.value ==value )||(this.right !=null&&this.right.value ==value)){
            return this;
        }else {
            if (value<this.value && this.left!=null){
                return this.left.searchParent(value);
            }else if (value>=this.value && this.right!=null){
                return this.right.searchParent(value);
            }else {
                return null;
            }
        }
    }
}
